<template>
  <div>
      <div class="header-content">
        <el-card style="width:100%">
        <el-form ref="searchRef" :model="query" :inline="true" >
          <el-form-item label="患者" prop="trainer">
            <el-select v-model="query.trainer" @change="getTrainerDates" style="width:220px;">
              <el-option v-for="item in trainerList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="训练时间" prop="time">
            <el-select v-model="query.time" multiple :disabled="!query.trainer" style="width:220px;">
              <el-option v-for="item in timeList" :key="item.date" :value="item.date" :label="item.date"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="time">
            <el-button type="primary" @click="searchReport" :disabled="!(query.trainer && query.time)">查看报告</el-button>
          </el-form-item>
        </el-form>
        </el-card>
      </div>
      <div class="operation-btn" v-if="trainerRecordData.length > 0">
          <el-button size="small" id="printId" v-print="'reportRef'"  type="success">打印报告</el-button>
          <el-button size="small" id="pdfId" @click="downloadPDF"  type="primary">下载报告</el-button>
      </div>
      <div v-if="trainerRecordData.length > 0" id="reportRef" class="content-dialog" style="margin-top:15px;">
        <div class="report-header">
          <h3 style="font-size: 22px !important;">{{unit_name}}</h3>
          <div style="font-size: 18px !important;margin:10px 0;">{{systemName}}训练报告</div>
          <!-- <el-button size="small" id="printId" class="print-btn no-print" v-print="'reportRef'"  type="success">打印报告</el-button>
          <el-button size="small" id="pdfId" class="down-btn no-print" @click="downloadPDF"  type="primary">下载报告</el-button> -->
          <!-- <el-button size="small" class="down-btn no-print" @click="downloadReport"  type="primary">下载报告</el-button> -->
        </div>
         <el-form ref="formRef" :model="trainerForm" :label-width="120">
          <el-divider content-position="left">基本信息</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="姓名"
                prop="name">
                {{trainerForm.name}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="性别"
                prop="gender">
              {{trainerForm.gender == 1 ? '男' : trainerForm.gender == 2 ? '女' : ''}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="年龄"
                prop="age"
              >
                {{trainerForm.age}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="出生日期"
                prop="birthday"
              >
              {{trainerForm.birthday}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="建档日期"
                prop="create_time"
              >
              {{trainerForm.create_time}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="家长"
                prop="contact"
              >
              {{trainerForm.contact}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="联系电话"
                prop="tel"
              >
              {{trainerForm.tel}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="家庭地址"
                prop="address"
              >
              {{trainerForm.address}}
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">诊断疾病</el-divider>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="病史"
                prop="medical_history"
              >
              {{trainerForm.medical_history}}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="诊断疾病"
                prop="disease"
              >
              {{m_multiTranslateByDict(trainerForm.disease ? JSON.parse(trainerForm.disease).join(",") : '', diseaseList, 'id', 'name')}}
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">常规检查信息</el-divider>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="检查项目"
                prop="check_items"
              >
              {{m_multiTranslateByDict(trainerForm.check_items ? JSON.parse(trainerForm.check_items).join(",") : '', checkItemsList, 'id', 'name')}}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="检查情况"
                prop="check_result"
              >
              {{trainerForm.check_result}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">训练记录</el-divider>
          <el-table :data="trainerRecordData">
            <el-table-column prop="course_date" label="训练日期" align="center"  show-overflow-tooltip></el-table-column>
            <el-table-column prop="course_time_name" label="训练场次" align="center"  show-overflow-tooltip></el-table-column>
            <el-table-column prop="start_time" label="训练时间" align="center"  show-overflow-tooltip>
              <template #default="{row}">
                {{row.start_time}}-{{row.end_time}}
              </template>
            </el-table-column>
            <el-table-column prop="scens_name" label="训练场景" align="center"  show-overflow-tooltip></el-table-column>
            <el-table-column prop="train_doctor" label="康复师" align="center"  show-overflow-tooltip>
              <template #default="{row}">
                {{toCase(row.train_doctor, doctorList, 'name', 'id')}}
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <br/>
          <div class="report-doctor" style="margin-bottom:15px;">
            <p> 签名：______________</p>
          </div>
          <div class="report-doctor">
            <p>报告日期：{{newDate}}</p>
          </div>
        </el-form>
      </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import { VTranRecordInfoService } from '@/api/service/vTranRecordInfoService'
import { DiseaseService } from "@/api/service/diseaseService";
import { m_multiTranslateByDict, toCase } from '@/utils/toCase';
import { CheckItemService } from "@/api/service/checkItemService";
import { DoctorService } from "@/api/service/doctorService";
import { TrainerService } from '@/api/service/trainerService';
import { DownloadService } from '@/api/service/downloadService';
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { saveAs } from 'file-saver'
import { generatePdf } from '@/utils/PDFGenerator'
import type { SiteConfig } from '@/types/siteConfig';
import  siteConfigService  from '@/api/service/siteConfigService'
import { useSystemStore } from '@/store/system';

const system = useSystemStore()
const systemName = ref()
systemName.value = localStorage.getItem('systemName') || '视听整合连续性训练系统'

watch(()=> system.systemName, (newValue, oldValue) => {
    systemName.value = newValue
})

const newDate = ref(dayjs(new Date().getTime()).format('YYYY年MM月DD日'))
const searchRef = ref<FormInstance>();

const trainerList = ref([])
const timeList = ref([])
const query = ref({
  trainer: null,
  time: []
})

const getTrainerList = async () => {
    trainerList.value = await VTranRecordInfoService.getTrainers()
};
getTrainerList();

const getTrainerDates = async (trainer_id) => {
    timeList.value = await VTranRecordInfoService.getTrainerDates(trainer_id)
    query.value.time = []
    if(timeList.value?.length > 0){
      timeList.value.map(item => {
         query.value.time.push(item.date)
      })
    }
};

const diseaseList = ref([]);
const getDiseaseList = async () => {
  const res = await DiseaseService.list();
  diseaseList.value = res;
};
getDiseaseList();

const checkItemsList = ref([]);
const getCheckItemsList = async () => {
  const res = await CheckItemService.list();
  checkItemsList.value = res;
};
getCheckItemsList();

const doctorList = ref([]);
const getDoctorList = async () => {
  const res = await DoctorService.list();
  doctorList.value = res;
};
getDoctorList();

const familyList = ref([
  { label: "三代同堂", value: 1 },
  { label: "核心家庭", value: 2 },
  { label: "单亲家庭", value: 2 },
]);

const getTrainer = async () => {
  const res = await TrainerService.findById(query.value.trainer)
  trainerForm.value = res
}

const courseDates = ref([])
const trainerRecordData = ref([])
const searchReport = async () => {
  getTrainer()
  const res = await VTranRecordInfoService.getTrainerRecords(query.value.trainer,query.value.time)
  trainerRecordData.value = res || []
  if(trainerRecordData.value?.length > 0){
    courseDates.value = []
    trainerRecordData.value.map(item => {
      courseDates.value.push(item.course_date)
    })
  }else {
    ElMessage.info('暂无训练记录情况')
  }
}
const print = () => {
    // 获取要打印的元素
  const content = document.getElementById('reportRef');
  // 创建一个新的window对象，用于打印
  const newWin = window.open('', '_blank');
  newWin.document.write(content.innerHTML);
  newWin.document.close();
  // 触发打印操作
  setTimeout(() => {
    newWin.print();
    newWin.close();
  }, 500); // 延迟确保内容已加载
}
const downloadReport = async () => {
  const params = {
    trainer_id: query.value.trainer,
    course_date: courseDates.value
  }
  const blob = await DownloadService.generateAssessmentReport(params)
  //console.log(blob)
  
  try {
    // 使用对话框方式下载报告
    const filePath = await DownloadService.downloadWithDialog(blob, '评估报告.docx')
    if (filePath) {
      ElMessage.success(`报告已保存到: ${filePath}`)
    }
  } catch (error) {
    console.error('下载报告失败:', error)
    // 如果对话框方式失败，回退到传统方式
    saveAs(blob, '评估报告.docx')
  }
}


// let username: string | null = localStorage.getItem('vuems_name');
const unit_name = ref()
unit_name.value = localStorage.getItem('unit_name') || ''
watch(()=> system.unit_name, (newValue, oldValue) => {
    unit_name.value = newValue
})
const loading = ref(false)
const downloadPDF = async() => {
  // const siteConfig =  await siteConfigService.getById(1);
  // const siteName = siteConfig.unit_name
  if(loading.value)return
  loading.value = true;
  await new Promise(resolve => setTimeout(resolve, 50)) // 让浏览器先渲染 loading
  try {
    await generatePdf('reportRef', '评估报告', {
      watermarkText: [unit_name.value,dayjs(new Date(new Date().getTime())).format('YYYY-MM-DD HH:mm:ss')],
      watermarkOptions: {
        opacity: 0.1,
        fontSize: 16,
        color: '#999999'
      }
    })
  } catch (e) {
    console.log('error',e)
    loading.value = false;
  } finally {
    loading.value = false;
  }
}
//创建一个将字符串转换为utf-8编码的函数
/**
 * 将UTF-8编码的字节数组转换为字符串
 * @param bytes UTF-8编码的字节数组
 * @returns 解码后的字符串
 */
// export const utf8ToString = (bytes: Uint8Array): string => {
//     // 使用TextDecoder进行解码
//     const decoder = new TextDecoder('utf-8');
//     return decoder.decode(bytes);
// };
/**
 * 将字符串转换为UTF-8编码的字节数组
 * @param str 要转换的字符串
 * @returns UTF-8编码的字节数组
 */
// export const stringToUtf8 = (str: string): Uint8Array => {
//     // 使用TextEncoder进行编码
//     const encoder = new TextEncoder();
//     return encoder.encode(str);
// };


let trainerForm = ref({
  // basis
  name: null,
  gender: null,
  age: null,
  birthday: null,
  family_structure: null,
  contact: null,
  tel: null,
  address: null,
  // 诊断疾病
  medical_history: null,
  disease: null,
  //常规检查信息
  check_items: null,
  check_result: null,
  train_doctor: null,
  charge_doctor: null,
});


</script>
<style scoped>

.header-content {
  display: flex;
  width: 100%;
}
.report-header {
  width: 100%;
  text-align: center;
  /* position: relative; */
}

.print-btn {
  position: absolute;
  right: 100px;
  top: 0px;
}
.down-btn {
  position: absolute;
  right: 0px;
  top: 0px;
}

.operation-btn {
  display: flex;
  justify-content: flex-start;
  margin-top: 10px;
}

.content-dialog {
  width: 800px;
  border: 1px solid #e4e7ed;
  background-color: #fff;
  padding: 10px;
}

.content-dialog :deep(.el-divider__text) {
  color: var(--active-color);
}

.report-doctor {
  /* display: flex; */
  /* justify-content: flex-end; */
  width: 100%;
  text-align: start;
}

@media print {
  @page {
        size: 210mm 297mm;  /* or size: 794px 1123px;   */
    }
  #reportRef {
    /* width: 1570px !important; */
    /* margin: 0;
    padding: 0px; */
  }
  .no-print {
    display: none;
  }
}
</style>